package com.example.pc.videodemo

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.provider.CallLog
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.example.myapplication.rabbitmq.OnReceivedDataListener
import com.example.pc.videodemo.emq.MqttManager.Companion.instance
import com.example.pc.videodemo.emq.model.EmqConstant
import com.example.pc.videodemo.emq.model.MqttMassgeSubscribBase

/**
 * @author zzx
 */
class PhoneActivity : AppCompatActivity(), OnReceivedDataListener {
    private var btnCall: Button? = null
    private var btnHangup: Button? = null
    private var tvNum: TextView? = null
    private var num: String? = null
    private var type = 0
    override fun onReceivedData(receiveBean: MqttMassgeSubscribBase) {
        Log.i("onReceivedData", "onReceivedData: $receiveBean")
        if (receiveBean.code == EmqConstant.serverToAndroidEnum.hangUp.code) {
            onCallChangeListener?.onHangup()
            finish()
            //        EmqConstant.serverToAndroidEnum.offlie.code -> offline(receiveBean)
//        EmqConstant.serverToAndroidEnum.occupy.code -> occupy()
//        EmqConstant.serverToAndroidEnum.onLine.code -> online(receiveBean)
//        EmqConstant.serverToAndroidEnum.hangUp.code -> hangUp(receiveBean)
//        EmqConstant.serverToAndroidEnum.call.code -> call(receiveBean)
//        EmqConstant.serverToAndroidEnum.ipAddress.code -> getIp(receiveBean)
        }
    }

    override fun onMqConnect() {}
    override fun onError() {}
    interface OnCallChangeListener {
        fun onAnswer()
        fun onHangup()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_phone)
        tvNum = findViewById(R.id.tv_phone_num)
        btnCall = findViewById(R.id.btn_call)
        btnHangup = findViewById(R.id.btn_hangup)
        num = intent.getStringExtra("num")
        type = intent.getIntExtra("type", 0)
        if (type == 0) {
        } else {
            btnCall?.setVisibility(View.GONE)
            /*
            Intent intent =new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:"+num));
            startActivity(intent);*/

//            call(num);
        }
        tvNum?.setText(num)
        btnHangup?.setOnClickListener(View.OnClickListener { //                TelephonyManager tm = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
//                tm.get
//                killPhoneCall();
//                dial(num);
            onCallChangeListener?.onHangup()
            finish()
        })
        btnCall?.setOnClickListener(View.OnClickListener {
            btnCall?.setVisibility(View.GONE)
            btnHangup?.setVisibility(View.VISIBLE)
            onCallChangeListener?.onAnswer()
        })
        if (instance != null) {
            instance?.setOnReceivedDataListener(this)
        }
    }

    private fun del() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALL_LOG) != PackageManager.PERMISSION_DENIED) return
        val resolver = contentResolver
        resolver.delete(CallLog.Calls.CONTENT_URI, "number=?", arrayOf(num))
    }

    /* private boolean killPhoneCall()
    {
        try
        {

            tryEndCall();

            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            Class classTelephony = Class.forName(telephonyManager.getClass().getName());
            Method methodGetITelephony = classTelephony.getDeclaredMethod("getITelephony");
            methodGetITelephony.setAccessible(true);
            Object telephonyInterface = methodGetITelephony.invoke(telephonyManager);
            Class telephonyInterfaceClass = Class.forName(telephonyInterface.getClass().getName());
            Method methodEndCall = telephonyInterfaceClass.getDeclaredMethod("endCall");
            methodEndCall.invoke(telephonyInterface);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            Log.d("TAG1", "hangupPhoneCall: " + e.toString());
            return false;
        }
        return true;
    }

    private void tryEndCall()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            try
            {

                TelecomManager telecomManager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
                if (telecomManager != null)
                {
                    boolean res = telecomManager.endCall();
                    Log.d("TAG1", "tryEndCall: " + res);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }*/
    override fun onDestroy() {
        super.onDestroy()
        del()
        if (instance != null) {
            instance?.removeListener(this)
        }
    }

    /**
     * 拒绝接听
     */
    /*
    public static void rejectCall(Context context)
    {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            try
            {
                Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
                IBinder binder = (IBinder) method.invoke(null, new Object[]{Context.TELEPHONY_SERVICE});
                ITelephony telephony = ITelephony.Stub.asInterface(binder);
                telephony.endCall();
            }
            catch (NoSuchMethodException e)
            {
                Log.d("TAG", "", e);
            }
            catch (ClassNotFoundException e)
            {
                Log.d("TAG", "", e);
            }
            catch (Exception e)
            {

            }
        }
        else
        {
            TelephonyManager mTelMgr = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
            Class<TelephonyManager> c = TelephonyManager.class;
            try
            {
                Method getITelephonyMethod = c.getDeclaredMethod("getITelephony", (Class[]) null);
                getITelephonyMethod.setAccessible(true);
                ITelephony iTelephony = null;
                System.out.println("End call.");
                iTelephony = (ITelephony) getITelephonyMethod.invoke(mTelMgr, (Object[]) null);
                iTelephony.endCall();
            }
            catch (Exception e)
            {
                e.printStackTrace();
                System.out.println("Fail to answer ring call.");
            }
        }


    }

    */
    /**
     * 接听电话
     */
    /*
    public static void acceptCall(Context context)
    {
        try
        {
            Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
            IBinder binder = (IBinder) method.invoke(null, new Object[]{Context.TELEPHONY_SERVICE});
            ITelephony telephony = ITelephony.Stub.asInterface(binder);
            telephony.answerRingingCall();
        }
        catch (Exception e)
        {
            acceptCall_4_1(context);
        }
    }

    */
    /**
     * 4.1版本以上接听电话
     */
    /*
    public static void acceptCall_4_1(Context context)
    {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        ;
        //模拟无线耳机的按键来接听电话
        // for HTC devices we need to broadcast a connected headset
        boolean broadcastConnected = MANUFACTURER_HTC.equalsIgnoreCase(Build.MANUFACTURER) && !audioManager.isWiredHeadsetOn();
        if (broadcastConnected)
        {
            broadcastHeadsetConnected(context, false);
        }
        try
        {
            try
            {
                Runtime.getRuntime().exec("input keyevent " + Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
            }
            catch (IOException e)
            {
                // Runtime.exec(String) had an I/O problem, try to fall back
                String enforcedPerm = "android.permission.CALL_PRIVILEGED";
                Intent btnDown = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
                Intent btnUp = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
                context.sendOrderedBroadcast(btnDown, enforcedPerm);
                context.sendOrderedBroadcast(btnUp, enforcedPerm);
            }
        }
        finally
        {
            if (broadcastConnected)
            {
                broadcastHeadsetConnected(context, false);
            }
        }
    }

    private static void broadcastHeadsetConnected(Context context, boolean connected)
    {
        Intent i = new Intent(Intent.ACTION_HEADSET_PLUG);
        i.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
        i.putExtra("state", connected ? 1 : 0);
        i.putExtra("name", "mysms");
        try
        {
            context.sendOrderedBroadcast(i, null);
        }
        catch (Exception e)
        {
        }
    }*/
    companion object {
        private var onCallChangeListener: OnCallChangeListener? = null
        fun show(context: Context, num: String?, onCallChangeListener: OnCallChangeListener?, i: Int) {
            val intent1 = Intent(context, PhoneActivity::class.java)
            Companion.onCallChangeListener = onCallChangeListener
            intent1.putExtra("num", num)
            intent1.putExtra("type", i)
            intent1.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent1)
        }
    }
}